package com.woniu.rabbitMq.service;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson2.JSONObject;
import com.woniu.common.dto.*;
import com.woniu.common.util.GetUserInfoUtil;
import com.woniu.common.util.ResponseData;
import com.woniu.rabbitMq.feign.SkuFeign;
import com.woniu.rabbitMq.feign.UserFeign;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

import static com.woniu.common.constant.MqConstant.Exchange.ORDER_EXCHANGE;
import static com.woniu.common.constant.MqConstant.Exchange.SKU_ORDER_EXCHANGE;
import static com.woniu.common.constant.MqConstant.RoutingKey.*;
import static com.woniu.common.util.SendMessageUtil.sendMsg;

@Service
@Slf4j
public class RabbitService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SkuFeign skuFeign;

    @Value("${snowflake.workerId}")
    private long workerId;
    @Value("${snowflake.datacenterId}")
    private long datacenterId;

    /**
     * 话费充值
     *
     * @param rechargeOrderDto
     * @return
     */
    public ResponseData<?> addRechargeOrder(RechargeOrderDto rechargeOrderDto) {

        //生成订单ID
        Long orderNum = IdUtil.getSnowflake(workerId, datacenterId).nextId();
        String phone = rechargeOrderDto.getPhone();
        BigDecimal price = rechargeOrderDto.getPrice();
        BigDecimal totalPrice = rechargeOrderDto.getTotalPrice();

        JSONObject orderJson = new JSONObject(3);
        orderJson.put("phone",phone);
        orderJson.put("price",price);
        orderJson.put("orderNum",orderNum);
        orderJson.put("totalPrice",totalPrice);

        //订单服务
        sendMsg(stringRedisTemplate,rabbitTemplate,ORDER_EXCHANGE,ORDER_ROUTING_KEY,orderJson.toString());

        // (4): ttl消息
        sendMsg(stringRedisTemplate,rabbitTemplate,ORDER_EXCHANGE,TTL_ORDER_ROUTING_KEY,orderJson.toString());

        return new ResponseData<>().ok(orderNum.toString());
    }


    public ResponseData<?> addSkuOrder(SkuOrderDto skuOrderDto) {
        //判断库存是否不足
        //首先获得新的想要购买的数量
        List<CartItemDto> cartItems = skuOrderDto.getItems();
        for (CartItemDto cartItem : cartItems) {
            //通过skuId查下面库存
            Long skuStore = skuFeign.querySkuCount(cartItem.getSkuId()).getSkuStore();
            SkuDto skuDto = skuFeign.querySkuCount(cartItem.getSkuId());
            SpuDto spuDto = skuFeign.querySpu(skuDto.getSpuId());
            if (cartItem.getQuantity() > skuStore.intValue()) {//如果有不足的
                return new ResponseData<>(500,
                        spuDto.getSpuName()+skuDto.getColor()+"目前库存不足,现有量:"
                                + skuStore,null);
            }
        }
        //生成订单ID
        long orderId = IdUtil.getSnowflake(workerId, datacenterId).nextId();

        JSONObject skuOrderJson = new JSONObject(1);
        skuOrderJson.put("skuOrderDto",skuOrderDto);
        skuOrderJson.put("orderId",orderId);
        //订单服务
        sendMsg(stringRedisTemplate,rabbitTemplate,SKU_ORDER_EXCHANGE,SKU_ORDER_ROUTING_KEY,skuOrderJson.toString(),null);

        //ttl
        sendMsg(stringRedisTemplate,rabbitTemplate,SKU_ORDER_EXCHANGE,TTL_SKU_ORDER_ROUTING_KEY,skuOrderJson.toString(),null);

        return new ResponseData<>().ok(String.valueOf(orderId));
    }

    public ResponseData<?> addRechargeOrderForJifen(RechargeOrderJiFenDto rechargeOrderDto) {
        //生成订单ID
        Long orderNum = IdUtil.getSnowflake(workerId, datacenterId).nextId();
        String phone = rechargeOrderDto.getPhone();
        Integer integral = rechargeOrderDto.getIntegral();

        JSONObject orderJson = new JSONObject(3);
        orderJson.put("phone",phone);
        orderJson.put("integral",integral);
        orderJson.put("orderNum",orderNum);


        //订单服务
        sendMsg(stringRedisTemplate,rabbitTemplate,ORDER_EXCHANGE,ORDER_ROUTING_KEY,orderJson.toString());

        // (4): ttl消息
        sendMsg(stringRedisTemplate,rabbitTemplate,ORDER_EXCHANGE,TTL_ORDER_ROUTING_KEY,orderJson.toString());

        return new ResponseData<>().ok(orderNum.toString());
    }

    public ResponseData<?> addJifenRechargeOrder(RechargeOrderJiFenDto rechargeOrderDto) {
        //生成订单ID
        Long orderNum = IdUtil.getSnowflake(workerId, datacenterId).nextId();
        String phone = rechargeOrderDto.getPhone();
        Integer integral = rechargeOrderDto.getIntegral();


        JSONObject orderJson = new JSONObject(3);
        orderJson.put("phone",phone);
        orderJson.put("integral",integral);
        orderJson.put("orderNum",orderNum);


        //订单服务
        sendMsg(stringRedisTemplate,rabbitTemplate,ORDER_EXCHANGE,JIFEN_ROUTING_KEY,orderJson.toString());

        // (4): ttl消息
        sendMsg(stringRedisTemplate,rabbitTemplate,ORDER_EXCHANGE,TTL_JIFEN_ROUTING_KEY,orderJson.toString());

        return new ResponseData<>().ok(orderNum.toString());
    }

    @Autowired
    private UserFeign userFeign;
    @SneakyThrows
    public ResponseData<?> addSkuOrderForJifen(SkuOrderJifenDto skuOrderJifenDto) {
        //判断库存是否不足
        //首先获得新的想要购买的数量
            //通过skuId查下面库存

            SkuDto skuDto = skuFeign.queryJifenSkuCount(skuOrderJifenDto.getSkuId());
            Long skuStore = skuDto.getSkuStore();
            SpuDto spuDto = skuFeign.querySpu(skuDto.getSpuId());
            if (skuOrderJifenDto.getBuyNum() > skuStore.intValue()) {//如果有不足的
                return new ResponseData<>(500,
                        spuDto.getSpuName()+skuDto.getColor()+"目前库存不足,现有量:"
                                + skuStore,null);
            }
        //生成订单ID
        long orderId = IdUtil.getSnowflake(workerId, datacenterId).nextId();

        UserDto userDto = GetUserInfoUtil.getUserInfo();
        skuOrderJifenDto.setPhone(userDto.getPhone());
        JSONObject skuOrderJson = new JSONObject(1);
        skuOrderJson.put("skuOrderDto",skuOrderJifenDto);
        skuOrderJson.put("orderId",orderId);
        skuOrderJson.put("user",userDto);
        //订单服务
        sendMsg(stringRedisTemplate,rabbitTemplate,SKU_ORDER_EXCHANGE,SKU_JIFEN_ORDER_ROUTING_KEY,skuOrderJson.toString(),null);

        //ttl
        sendMsg(stringRedisTemplate,rabbitTemplate,SKU_ORDER_EXCHANGE,TTL_SKU_JIFEN_ORDER_ROUTING_KEY,skuOrderJson.toString(),null);

        return new ResponseData<>().ok(String.valueOf(orderId));
    }
}
